package com.yantong.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.yantong.annotation.Auth;
import com.yantong.constant.BusinessCode;
import com.yantong.controller.BaseController;
import com.yantong.enums.PayChannelEnum;
import com.yantong.mapper.TBusinessCardMapper;
import com.yantong.mapper.XLoginInfoMapper;
import com.yantong.pay.yfz.pay.YFZPayutil;
import com.yantong.pojo.*;
import com.yantong.pojo.vo.BrokerageVo;
import com.yantong.result.ResultVo;
import com.yantong.service.*;
import com.yantong.utils.CommonUtils;
import com.yantong.utils.CusAccessObjectUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: juzi
 * @date: 2021/10/25
 * @time: 16:12
 */
@ApiIgnore
@Controller
@RequestMapping("/wxapi/vip")
public class ApiVipController extends BaseController {

    @Autowired
    private MemberService memberService;
    @Autowired
    private ShipcardService shipcardService;
    @Autowired
    private ConfigService configService;
    @Autowired
    private MyWxpayService myWxpayService;
    @Autowired
    private TBusinessCardMapper tBusinessCardMapper;
    @Autowired
    private YFZPayutil yfzPayutil;
    @Autowired
    private PayChannelService payChannelService;
    @Autowired
    private CentreService centreService;
    @Autowired
    private XLoginInfoMapper xLoginInfoMapper;


    @Value("${yfz.notify}")
    private String yfzNotifyUrl;

    @Value("${weixin.pay.notify}")
    private String notifyUrl;

    private static final Logger logger = LoggerFactory.getLogger(ApiVipController.class);



    private static final double VIP_PRICE = 199;

    /**
     * 余额购买会员（电子名片购买名片）
     */
    @RequestMapping("/yupayCard")
    @ResponseBody
    @Auth(arg = 0)
    public ResultVo buyVipByBalanceCard(Long memberId, String code, Long shipcardId, Long centreId, String level) {
        int result = 0;
        //余额购买会员
        result = memberService.buyVipByBalanceCard(memberId, code, level);
        ResultVo resultVo = new ResultVo();
        resultVo.put("success", true);
        resultVo.put("data", result);
        return resultVo;
    }

    /**
     * 微信支付购买会员
     */
    @RequestMapping("/wxpay")
    @ResponseBody
    @Auth(arg = 0)
    public ResultVo buyVipByWeixin(Long memberId, String openId, String code, Long centreId, Long shipcardId,HttpServletRequest request) {
        Shipcard shipcard = null;
        ResultVo resultVo = new ResultVo();
        if (shipcardId != null) {
            //购物卡
            shipcard = shipcardService.selectByPrimaryKey(shipcardId);
            ShipcardRecord shipcardRecord = new ShipcardRecord();
            shipcardRecord.setMid(memberId);
            shipcardRecord.setShipcardId(shipcard.getId());
            //德奥用户购买了几次
            Integer num = shipcardService.getTotal(shipcardRecord);
            if (num != null && num >= shipcard.getNum()) {
                //超过了购买限制
                return ResultVo.error(BusinessCode.MEMBER_SHIPCARD_ALOT);
            }
        }
        String payNo = CommonUtils.getSn("X_OC_D");
        String desc = "升级会员";
        JSONObject attach = new JSONObject();
        if (shipcardId == null) {
            attach.put("type", 1);
        } else {
            attach.put("type", 2);
            //购物卡的订单编号
        }
        attach.put("memberId", memberId);
        attach.put("code", code);
        attach.put("centreId", centreId);
        if (shipcardId != null) {
            attach.put("shipcardId", shipcardId);
        }
        WxPayMpOrderResult result = null;
        boolean success = false;

        while (!success) {
            try {
                double price = VIP_PRICE;
                TradeConfig config = configService.getTradeConfig(centreId);
                if (shipcardId == null) {
                    if (config != null) {
                        if (config.getVipPrice() != null) {
                            price = config.getVipPrice();
                        }
                    }
                } else {
                    if (shipcard == null) {
                        shipcard = shipcardService.selectByPrimaryKey(shipcardId);
                        //充值卡价格
                        price = shipcard.getPayment().doubleValue();
                    } else {
                        //充值卡价格
                        price = shipcard.getPayment().doubleValue();
                    }
                }
                 result = myWxpayService.createJSPayRequest(openId, desc, payNo
                        , price, notifyUrl, CusAccessObjectUtil.getIpAddress(request), attach.toJSONString());

                resultVo.put("success", true);
                resultVo.put("data", result);

                success = true;
            } catch (Exception e) {
                return ResultVo.error(e.getMessage());
            }
        }
        return resultVo;
    }


    /**
     * 本地生活微信支付购买王权会员
     */
    @RequestMapping("/wxpayLocalLifeCard")
    @ResponseBody
    @Auth(arg = 0)
    public ResultVo buyLocalLifeVipWeixinCard(Long memberId, String openId, String code, Integer payMethod,Long centreId, Long shipcardId, String level, Integer vipType, HttpServletRequest request) {
        //vipType 0季度 1年
        ResultVo resultVo = new ResultVo();
        String payNo = CommonUtils.getSn("X_OC_D");
        String desc = "升级王权会员";
        JSONObject attach = new JSONObject();


        attach.put("type", WXPAY_LOCALLIFE_VIP);
        if (StringUtils.isNotBlank(level)) {
            attach.put("type", level);
        }
        attach.put("vipType", vipType);
        attach.put("memberId", memberId);
        attach.put("code", code);
        attach.put("centreId", centreId);
        try {
            double price = 0.00;
            if (null == centreId) {
                Centre platCenter = centreService.getPlatCenter();
                centreId = platCenter.getCentreId();
            }
            LifeConfig config = configService.getLifeConfig(centreId);
            if (config != null && vipType != null) {
                if (config.getKingshipVipQuarter() != null && vipType == 0) {
                    price = Double.parseDouble(config.getKingshipVipQuarter());
                } else if (config.getKingshipVipYear() != null && vipType == 1) {
                    price = Double.parseDouble(config.getKingshipVipYear());
                }
            }

            //获取一条可用支付通道
            PayChannel payChannel = payChannelService.getFirstChannel(centreId);
            logger.info("王权会员购买支付通道查询===={} , ====price=={}" , JSONObject.toJSONString(payChannel),price);
//            if (StringUtils.isNotBlank(payChannel.getChannelCode()) && payChannel.getChannelCode().equals(PayChannelEnum.YPL.getCode()) && price > 0.01) {
                Centre centre = centreService.getCentreById(centreId);
                Member teamMember = new Member();
                Member member = memberService.getByKey(memberId);
                Order order = new Order();
                order.setOutTradeNo(payNo);
                List<OrderProduct> orderProductList = new ArrayList<>();
                OrderProduct orderProduct = new OrderProduct();
                orderProduct.setProductId(99L);
                orderProduct.setProductName("王权会员升级");
                orderProduct.setPrice(BigDecimal.valueOf(price));
                orderProduct.setTotal(1);
                orderProductList.add(orderProduct);
            XLoginInfo xLoginInfo = new XLoginInfo();
            xLoginInfo.setMobile(member.getLoginMobile());
            xLoginInfo = xLoginInfoMapper.selectOne(xLoginInfo);
            member.setAppOpenid(xLoginInfo.getOpenId());
                return yfzPayutil.getPayConfig(order, price, centre, orderProductList, member, JSON.toJSONString(attach), payMethod == null ? 1 : payMethod, true, yfzNotifyUrl, request, teamMember);
//            } else {
//                WxPayMpOrderResult result = myWxpayService.createJSPayRequest(openId, desc, payNo
//                        , price, notifyUrl, CusAccessObjectUtil.getIpAddress(request), attach.toJSONString());
//                resultVo.put("data", result);
//                resultVo.put("success", true);
//            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error(e.getMessage());
        }

//        return resultVo;
    }


    /**
     * 微信支付购买会员
     */
    @RequestMapping("/wxpayCard")
    @ResponseBody
    @Auth(arg = 0)
    public ResultVo buyVipByWeixinCard(Long memberId, String openId, String code, Long centreId, Long shipcardId, String level, HttpServletRequest request) {
        Shipcard shipcard = null;
        ResultVo resultVo = new ResultVo();
        if (shipcardId != null) {
            //购物卡
            shipcard = shipcardService.selectByPrimaryKey(shipcardId);
            ShipcardRecord shipcardRecord = new ShipcardRecord();
            shipcardRecord.setMid(memberId);
            shipcardRecord.setShipcardId(shipcard.getId());
            //德奥用户购买了几次
            Integer num = shipcardService.getTotal(shipcardRecord);
            if (num != null && num >= shipcard.getNum()) {
                //超过了购买限制
                return ResultVo.error(BusinessCode.MEMBER_SHIPCARD_ALOT);
            }
        }
        String payNo = CommonUtils.getSn("X_OC_D");
        String desc = "电子名片";
        JSONObject attach = new JSONObject();
        if (shipcardId == null) {
            attach.put("type", 1);
        } else {
            attach.put("type", 2);
            //购物卡的订单编号
        }

        if (StringUtils.isNotBlank(level)) {
            attach.put("type", level);
        }

        attach.put("memberId", memberId);
        attach.put("code", code);
        attach.put("centreId", centreId);
        if (shipcardId != null) {
            attach.put("shipcardId", shipcardId);
        }
        WxPayMpOrderResult result = null;
        boolean success = false;

        while (!success) {
            try {
                double price = VIP_PRICE;
                CardConfig cardConfig = configService.getCardConfig(centreId);
                if (shipcardId == null) {
                    if (cardConfig != null) {
                        if (cardConfig.getVipGradeAmount() != null) {
                            price = cardConfig.getVipGradeAmount();
                        }
                    }
                } else {
                    if (shipcard == null) {
                        shipcard = shipcardService.selectByPrimaryKey(shipcardId);
                        //充值卡价格
                        price = shipcard.getPayment().doubleValue();
                    } else {
                        //充值卡价格
                        price = shipcard.getPayment().doubleValue();
                    }
                }

                //获取VIP的支付价格
                if (level != null) {
                    BrokerageVo brokerageVo = tBusinessCardMapper.getBrokerageById(2L);
                    if (brokerageVo != null) {
                        price = brokerageVo.getCount().doubleValue();
                    }
                }

                result = myWxpayService.createJSPayRequest(openId, desc, payNo
                        , price, notifyUrl, CusAccessObjectUtil.getIpAddress(request), attach.toJSONString());
                resultVo.put("success", true);
                resultVo.put("data", result);
                success = true;
            } catch (Exception e) {
                return ResultVo.error(e.getMessage());
            }
        }
        return resultVo;
    }
}
